package com.bandaotixi.cashier.api.common.util;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.bandaotixi.cashier.api.system.model.DictItem;
import com.bandaotixi.cashier.api.system.service.DictItemService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.util.Map;

public class DictUtil {

    private static final Cache<String, Map<String, String>> DICT_CACHE = CacheUtil.newTimedCache(1000 * 60 * 60);

    /**
     * 获取key，value反转的字典
     */
    public static Map<String, String> getDictMapReverse(String dictType) {
        DictItemService dictItemService = SpringUtil.getBean(DictItemService.class);
        return dictItemService.list(new LambdaQueryWrapper<DictItem>()
                        .eq(DictItem::getDictCode, dictType)
                        .eq(DictItem::getStatus, 1)
                )
                .stream()
                .collect(java.util.stream.Collectors.toMap(DictItem::getLabel, DictItem::getValue, (k1, k2) -> k1));
    }

    public static Map<String, String> getDictMap(String dictType) {
        DictItemService dictItemService = SpringUtil.getBean(DictItemService.class);
        return dictItemService.list(new LambdaQueryWrapper<DictItem>()
                        .eq(DictItem::getDictCode, dictType)
                        .eq(DictItem::getStatus, 1)
                )
                .stream()
                .collect(java.util.stream.Collectors.toMap(DictItem::getValue, DictItem::getLabel));
    }

    public static Map<String, String> getDictMapOfCache(String dictType) {
        Map<String, String> dictMap = DICT_CACHE.get(dictType);
        if (dictMap == null) {
            dictMap = getDictMap(dictType);
            DICT_CACHE.put(dictType, dictMap);
        }
        return dictMap;
    }
}
